﻿using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;

public class HealthUIController : MonoBehaviour
{

    private Transform cameraTran;
    private Transform MyTran;
    private Image healthImg;
    private Tween SliderTween;
    private float endHealthValue = 1;
    private Action TweenOverAction;

    /// <summary>
    /// 血条初始化
    /// </summary>
    private void Start()
    {
        cameraTran = Camera.main.transform;
        MyTran = transform;
        healthImg = MyTran.Find("health").GetComponent<Image>();
        //初始化血条UI,暂停,动画结束不消失
        SliderTween = DOTween.To(() => healthImg.fillAmount, x => healthImg.fillAmount = 0, endHealthValue, 0.2f);
        SliderTween.Pause();
        SliderTween.SetAutoKill(false);
        TweenOverAction = null;
        SliderTween.OnStepComplete(()=> TweenOverAction());
        healthImg.fillAmount = 1;
        //开始持续面对镜头
        InvokeRepeating("FaceToCamere", 0, 0.05f);
    }

    /// <summary>
    /// 持续面向摄像机
    /// </summary>
    public void FaceToCamere()
    {
        MyTran.LookAt(cameraTran);
    }

    /// <summary>
    /// 更新血条值,0至1之间
    /// 动画结束后检测结束委托
    /// </summary>
    public void UpdataHealth(float healthValue,Action TweenCallBack = null)
    {
        //如果有回调，清空回调方法，添加新的回调
        if (TweenOverAction != null)
        {
            if (TweenOverAction != null)
                TweenOverAction = null;
            TweenOverAction = TweenCallBack;
        }
        endHealthValue = healthValue;
        SliderTween.Play();
    }
}
